package com.banshuibao.bsb_android.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.banshuibao.bsb_android.model.DownloadAudioModel;
import com.banshuibao.bsb_android.model.DownloadInfo;

public class DataSet {
    private static String DOWNLOADINFO = "downloadinfo";
    private static String AUDIOINFO = "downloadaudioinfo";
    private static String VIDEOPOSITION = "videoposition";

    private static Map<String, DownloadInfo> downloadInfoMap;

    private static Map<String, DownloadAudioModel> downloadAudioInfoMap;

    private static SQLiteOpenHelper sqLiteOpenHelper;

    public static void init(Context context, String userId) {
        DOWNLOADINFO = "downloadinfo" + userId;
        AUDIOINFO = "downloadaudioinfo" + userId;
        sqLiteOpenHelper = new SQLiteOpenHelper(context, "jsb_media" + userId, null, 1) {
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
                String sql = "CREATE TABLE IF NOT EXISTS " + DOWNLOADINFO + "(" +
                        "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        "videoId VERCHAR, " +
                        "title VERCHAR, " +
                        "progress DECIMAL, " +
                        "progressText VERCHAR, " +
                        "status INTEGER, " +
                        "createTime DATETIME, " +
                        "definition INTEGER," +
                        "name VERCHAR," +
                        "uuid VERCHAR," +
                        "imgUrl VERCHAR," +
                        "shareUrl VERCHAR," +
                        "img VERCHAR)";

                String sqlAaudio = "CREATE TABLE IF NOT EXISTS " + AUDIOINFO + "(" +
                        "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        "uuid VERCHAR, " +
                        "url VERCHAR, " +
                        "content VERCHAR, " +
                        "progress INTEGER, " +
                        "progressText VERCHAR, " +
                        "status INTEGER, " +
                        "indexTask INTEGER, " +
                        "createTime DATETIME, " +
                        "voiceTime VERCHAR, " +
                        "groupId VERCHAR," +
                        "name VERCHAR," +
                        "question VERCHAR, " +
                        "duty VERCHAR," +
                        "img VERCHAR)";

                /*String videoPositionSql = "CREATE TABLE IF NOT EXISTS videoposition(id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        "videoId VERCHAR, " +
                        "position INTEGER)";*/

                db.execSQL(sql);
                db.execSQL(sqlAaudio);
                //db.execSQL(videoPositionSql);

            }
        };

        downloadInfoMap = new HashMap<>();
        downloadAudioInfoMap = new HashMap<>();
        reloadData();
    }

    public static void clear() {
        DOWNLOADINFO = "downloadinfo";
        AUDIOINFO = "downloadaudioinfo";
        if (downloadAudioInfoMap != null && downloadInfoMap != null) {
            if (downloadInfoMap.size() > 0 && downloadAudioInfoMap.size() > 0)
                saveData();
            downloadAudioInfoMap.clear();
            downloadInfoMap.clear();
        }
        try {
            sqLiteOpenHelper.close();
        } catch (Exception e) {
            LogUtil.e(e.getMessage());
        }
    }


    private static void reloadData() {

        SQLiteDatabase db = sqLiteOpenHelper.getReadableDatabase();
        Cursor cursor = null;
        try {
            // 重载下载信息
            synchronized (downloadInfoMap) {
                cursor = db.rawQuery("SELECT * FROM ".concat(DOWNLOADINFO), null);
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    try {
                        DownloadInfo downloadInfo = buildDownloadInfo(cursor);
                        downloadInfoMap.put(downloadInfo.getVideoId(), downloadInfo);

                    } catch (ParseException e) {
                        Log.e("Parse date error", e.getMessage());
                    }
                }
            }

            // 重载下载信息
            synchronized (downloadAudioInfoMap) {
                cursor = db.rawQuery("SELECT * FROM ".concat(AUDIOINFO), null);
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    try {
                        DownloadAudioModel audioModel = buildDownloadAudioInfo(cursor);
                        downloadAudioInfoMap.put(audioModel.getUuid(), audioModel);

                    } catch (ParseException e) {
                        Log.e("Parse date error", e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            Log.e("cursor error", e.getMessage());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public static void saveData() {
        if (sqLiteOpenHelper == null)
            return;
        SQLiteDatabase db = sqLiteOpenHelper.getReadableDatabase();
        db.beginTransaction();

        try {
            //清除当前数据
            db.delete(DOWNLOADINFO, null, null);

            for (DownloadInfo downloadInfo : downloadInfoMap.values()) {
                ContentValues values = new ContentValues();
                values.put("videoId", downloadInfo.getVideoId());
                values.put("title", downloadInfo.getTitle());
                values.put("progress", downloadInfo.getProgress());
                values.put("progressText", downloadInfo.getProgressText());
                values.put("status", downloadInfo.getStatus());
                values.put("definition", downloadInfo.getDefinition());
                values.put("name", downloadInfo.getName());
                values.put("img", downloadInfo.getImg());
                values.put("uuid", downloadInfo.getUuid());
                values.put("imgUrl", downloadInfo.getImgUrl());
                values.put("shareUrl", downloadInfo.getShareUrl());

                SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                values.put("createTime", formater.format(downloadInfo.getCreateTime()));

                db.insert(DOWNLOADINFO, null, values);
            }

            //清除当前数据
            db.delete(AUDIOINFO, null, null);

            for (DownloadAudioModel audioModel : downloadAudioInfoMap.values()) {
                ContentValues values = new ContentValues();
                values.put("uuid", audioModel.getUuid());
                values.put("url", audioModel.getUrl());
                values.put("content", audioModel.getContent());
                values.put("groupId", audioModel.getGroupId());
                values.put("name", audioModel.getName());
                values.put("duty", audioModel.getDuty());
                values.put("img", audioModel.getImg());
                values.put("progressText", audioModel.getProgressText());
                values.put("question", audioModel.getQuestion());
                values.put("createTime", audioModel.getCreateTime());
                values.put("progress", audioModel.getProgress());
                values.put("status", audioModel.getStatus());
                values.put("voiceTime", audioModel.getVoiceTime());
                values.put("indexTask", audioModel.getIndexTask());

                db.insert(AUDIOINFO, null, values);
            }

            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e("db error", e.getMessage());
        } finally {
            db.endTransaction();
        }

        db.close();
    }

    public static List<DownloadInfo> getDownloadInfos() {

        return new ArrayList<>(downloadInfoMap.values());
    }

    public static boolean hasDownloadInfo(String Title) {
        return downloadInfoMap.containsKey(Title);
    }

    public static DownloadInfo getDownloadInfo(String Title) {
        return downloadInfoMap.get(Title);
    }

    public static void addDownloadInfo(DownloadInfo downloadInfo) {
        synchronized (downloadInfoMap) {
            if (downloadInfoMap.containsKey(downloadInfo.getTitle())) {
                return;
            }

            downloadInfoMap.put(downloadInfo.getTitle(), downloadInfo);
        }
    }

    public static void removeDownloadInfo(String title) {
        synchronized (downloadInfoMap) {
            downloadInfoMap.remove(title);
        }
    }

    public static void updateDownloadInfo(DownloadInfo downloadInfo) {
        synchronized (downloadInfoMap) {
            downloadInfoMap.put(downloadInfo.getTitle(), downloadInfo);
        }

    }

    //
    public static List<DownloadAudioModel> getDownloadAudioInfos() {

        return new ArrayList<>(downloadAudioInfoMap.values());
    }

    public static boolean hasDownloadAudioInfo(String uuid) {
        return downloadAudioInfoMap.containsKey(uuid);
    }

    public static DownloadAudioModel getDownloadAudioInfo(String uuid) {
        return downloadAudioInfoMap.get(uuid);
    }

    public static void addDownloadAudiInfo(DownloadAudioModel downloadInfo) {
        synchronized (downloadAudioInfoMap) {
            if (downloadAudioInfoMap.containsKey(downloadInfo.getUuid())) {
                return;
            }
            downloadAudioInfoMap.put(downloadInfo.getUuid(), downloadInfo);
        }
    }

    public static void removeDownloadAudioInfo(String uuid) {
        synchronized (downloadAudioInfoMap) {
            downloadAudioInfoMap.remove(uuid);
        }
    }

    public static void updateDownloadAaudioInfo(DownloadAudioModel downloadInfo) {
        synchronized (downloadAudioInfoMap) {
            downloadAudioInfoMap.put(downloadInfo.getUuid(), downloadInfo);
        }

    }


    private static DownloadAudioModel buildDownloadAudioInfo(Cursor cursor) throws ParseException {
        DownloadAudioModel downloadInfo = new DownloadAudioModel();
        downloadInfo.setUuid(cursor.getString(cursor.getColumnIndex("uuid")));
        downloadInfo.setContent(cursor.getString(cursor.getColumnIndex("content")));
        downloadInfo.setUrl(cursor.getString(cursor.getColumnIndex("url")));
        downloadInfo.setCreateTime(cursor.getLong(cursor.getColumnIndex("createTime")));
        downloadInfo.setDuty(cursor.getString(cursor.getColumnIndex("duty")));
        downloadInfo.setGroupId(cursor.getString(cursor.getColumnIndex("groupId")));
        downloadInfo.setImg(cursor.getString(cursor.getColumnIndex("img")));
        downloadInfo.setName(cursor.getString(cursor.getColumnIndex("name")));
        downloadInfo.setQuestion(cursor.getString(cursor.getColumnIndex("question")));
        downloadInfo.setProgress(cursor.getDouble(cursor.getColumnIndex("progress")));
        downloadInfo.setProgressText(cursor.getString(cursor.getColumnIndex("progressText")));
        downloadInfo.setStatus(cursor.getInt(cursor.getColumnIndex("status")));
        downloadInfo.setVoiceTime(cursor.getString(cursor.getColumnIndex("voiceTime")));
        downloadInfo.setIndexTask(cursor.getInt(cursor.getColumnIndex("indexTask")));
        return downloadInfo;
    }

    private static DownloadInfo buildDownloadInfo(Cursor cursor) throws ParseException {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = formater.parse(cursor.getString(cursor.getColumnIndex("createTime")));
        DownloadInfo downloadInfo = new DownloadInfo(cursor.getString(cursor.getColumnIndex("videoId")),
                cursor.getString(cursor.getColumnIndex("title")),
                cursor.getInt(cursor.getColumnIndex("progress")),
                cursor.getString(cursor.getColumnIndex("progressText")),
                cursor.getInt(cursor.getColumnIndex("status")),
                createTime,
                cursor.getInt(cursor.getColumnIndex("definition")),
                cursor.getString(cursor.getColumnIndex("name")),
                cursor.getString(cursor.getColumnIndex("img")),
                cursor.getString(cursor.getColumnIndex("uuid")),
                cursor.getString(cursor.getColumnIndex("imgUrl")),
                cursor.getString(cursor.getColumnIndex("shareUrl")));
        return downloadInfo;
    }

    public static void insertVideoPosition(String videoId, int position) {

        SQLiteDatabase database = sqLiteOpenHelper.getWritableDatabase();
        if (database.isOpen()) {
            ContentValues values = new ContentValues();
            values.put("videoId", videoId);
            values.put("position", position);
            database.insert(VIDEOPOSITION, null, values);
            database.close();
        }
    }

    public static int getVideoPosition(String videoId) {
        int position = 0;
        SQLiteDatabase database = sqLiteOpenHelper.getReadableDatabase();
        if (database.isOpen()) {
            Cursor cursor = database.query(VIDEOPOSITION, new String[]{"position"}, "videoId=?", new String[]{videoId}, null, null, null);
            if (cursor.moveToFirst()) {
                position = cursor.getInt(cursor.getColumnIndex("position"));
            }
            cursor.close();
            database.close();
        }
        return position;
    }

    public static void updateVideoPosition(String videoId, int position) {
        SQLiteDatabase database = sqLiteOpenHelper.getWritableDatabase();
        if (database.isOpen()) {
            ContentValues values = new ContentValues();
            values.put("position", position);
            database.update(VIDEOPOSITION, values, "videoId=?", new String[]{videoId});
            database.close();
        }
    }
}
